import { defineStore } from 'pinia';
import { fetchEnum, type EnumItem } from '@/api';

interface EnumState {
  // key 为字典类型（dictType），value 为该类型下的枚举列表
  enums: Record<string, EnumItem[]>;
  loaded: boolean;
}

export const useEnumStore = defineStore('enum', {
  state: (): EnumState => ({
    enums: {},
    loaded: false,
  }),
  getters: {
    // 根据字典类型获取枚举列表
    getEnumByType:
      (state) =>
      (dictType: string): EnumItem[] => {
        return state.enums[dictType] || [];
      },
  },
  actions: {
    /**
     * 登录后调用一次，拉取所有枚举并按 dictType 分组缓存
     */
    async loadAllEnums(force = false) {
      if (this.loaded && !force) return;

      // fetchEnum 返回 HttpResponse<{ [dictType]: EnumItem[] }>
      const res = await fetchEnum();
      const data = (res.data || {}) as Record<string, EnumItem[]>;

      const map: Record<string, EnumItem[]> = {};
      Object.keys(data).forEach((dictType) => {
        map[dictType] = data[dictType] || [];
      });

      this.enums = map;
      console.log(this.enums, 'this.enums');
      this.loaded = true;
    },
  },
  persist: {
    pick: ['enums', 'loaded'],
    storage: localStorage,
  },
});
